package thread.abc;

/**
 * wait() 方法会释放资源 , notifyAll 通知所有线程进入就绪队列
 */
public class printABCOld {

    private volatile static int state = 0;

    public static void main(String[] args) {
        final Object t = new Object();

        Thread A = new Thread(() -> {
            // 设定打印10次
            for (int i = 0; i < 10; i++) {
                synchronized (t) {
                    // 如果不满足A的打印条件，则调用wait，一直阻塞
                    while (state % 3 != 0) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 执行到这里，表明满足条件，打印A，设置state
                    // 调用notifyAll方法
                    System.out.print("A");
                    state++;
                    t.notifyAll();
                }
            }
        });
        Thread B = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (t) {
                    while (state % 3 != 1) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B");
                    state++;
                    t.notifyAll();
                }
            }
        });
        Thread C = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (t) {
                    while (state % 3 != 2) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                    state++;
                    System.out.println(state);
                    t.notifyAll();
                }
            }
        });
        A.start();
        B.start();
        C.start();
    }
}